package com.tuanzi.loan.business.repository.distribution.impl;

import static com.tuanzi.loan.generated.jooq.loan.tables.CommProductChannel.COMM_PRODUCT_CHANNEL;
import static com.tuanzi.loan.generated.jooq.loan.tables.CommProductPrdid.COMM_PRODUCT_PRDID;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanDistributionActivity.LOAN_DISTRIBUTION_ACTIVITY;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanDistributionRecord.LOAN_DISTRIBUTION_RECORD;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.jooq.SelectConditionStep;
import org.jooq.SelectQuery;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import com.tuanzi.loan.business.repository.distribution.DistributionRecordRepository;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import com.tuanzi.loan.vo.request.distribution.DistributionRecordSearchRequest;
import com.tuanzi.loan.vo.response.distribution.GalaxyCardDistributionRecordSearchResponse;
import com.tuanzi.server.loan_base.util.PhoneNumNideUtil;
/**
 * 邀请明细统计 JOOQRepositoryImplement
 * @author JinRuiyang 2018/2/8 10:33:31
 */
@Repository
public class DistributionRecordRepositoryImpl extends JOOQBaseRepositoryPlus implements DistributionRecordRepository {

    public enum ShareType{
        QRCODE(0, "分享二维码"),
        WECHAT_FRIEND(1, "微信好友"),
        WECHAT_CIRCLE(2, "微信朋友圈"),
        QQ_FRIEND(3, "QQ好友");

        private Integer type;
        private String name;
        ShareType(Integer type, String name){
            this.type = type;
            this.name = name;
        }
        public static String get(Integer type){
            for (ShareType shareType : ShareType.values()){
                if (type.equals(shareType.type))
                    return shareType.name;
            }
            return "";
        }
    }

    @Override
    public Map<String, Integer> getProductList(){
        return dslContext.selectDistinct(COMM_PRODUCT_PRDID.NAME, COMM_PRODUCT_PRDID.PRDID)
                .from(COMM_PRODUCT_PRDID)
                .join(LOAN_DISTRIBUTION_RECORD).on(LOAN_DISTRIBUTION_RECORD.PRODUCT.eq(COMM_PRODUCT_PRDID.PRDID))
                .fetchMap(COMM_PRODUCT_PRDID.NAME, COMM_PRODUCT_PRDID.PRDID);
    }

    @Override
    public Map<String, Integer> getChannelList(){
        return dslContext.selectDistinct(COMM_PRODUCT_CHANNEL.CHANNEL_NAME, COMM_PRODUCT_CHANNEL.CHANNEL_CODE)
                .from(COMM_PRODUCT_CHANNEL)
                .join(LOAN_DISTRIBUTION_RECORD).on(LOAN_DISTRIBUTION_RECORD.CHANNEL.eq(COMM_PRODUCT_CHANNEL.CHANNEL_CODE))
                .fetchMap(COMM_PRODUCT_CHANNEL.CHANNEL_NAME, COMM_PRODUCT_CHANNEL.CHANNEL_CODE);
    }

    @Override
    public Map<String,String> getPlatformList(){
        Map<String,String> platform = new HashMap<>();
        platform.put("IOS", "ios");
        platform.put("安卓", "android");
        return platform;
    }

    @Override
    public Map<String, Long> getDistributionActivity() {
        return dslContext.selectDistinct(LOAN_DISTRIBUTION_ACTIVITY.NAME,LOAN_DISTRIBUTION_ACTIVITY.ID)
                .from(LOAN_DISTRIBUTION_ACTIVITY)
                .fetchMap(LOAN_DISTRIBUTION_ACTIVITY.NAME,LOAN_DISTRIBUTION_ACTIVITY.ID);
    }

    @Override
    public Page<GalaxyCardDistributionRecordSearchResponse> list(DistributionRecordSearchRequest searchRequest, Pageable pageable) {
        SelectConditionStep conditionStep = dslContext.select(
                    LOAN_DISTRIBUTION_RECORD.CREATE_TIME,
                    LOAN_DISTRIBUTION_RECORD.PLATFORM,
                    LOAN_DISTRIBUTION_RECORD.COMMISSION,
                    LOAN_DISTRIBUTION_RECORD.ORDER_ID,
                    LOAN_DISTRIBUTION_RECORD.SHARE_TYPE,
                    LOAN_DISTRIBUTION_RECORD.ID,
                    LOAN_DISTRIBUTION_RECORD.SUBORDINATE_PHONE,
                    LOAN_DISTRIBUTION_RECORD.SUPERIOR_PHONE,
                    COMM_PRODUCT_PRDID.NAME,
                    COMM_PRODUCT_CHANNEL.CHANNEL_NAME)
                .from(getTable())
                .leftJoin(COMM_PRODUCT_PRDID).on(COMM_PRODUCT_PRDID.PRDID.eq(LOAN_DISTRIBUTION_RECORD.PRODUCT))
                .leftJoin(COMM_PRODUCT_CHANNEL).on(COMM_PRODUCT_CHANNEL.CHANNEL_CODE.eq(LOAN_DISTRIBUTION_RECORD.CHANNEL))
                .where(DSL.trueCondition());
        if (Objects.nonNull(searchRequest.getStartTime()))
            conditionStep = conditionStep.and(LOAN_DISTRIBUTION_RECORD.CREATE_TIME.ge(new Timestamp(searchRequest.getStartTime().getTime())));
        if (Objects.nonNull(searchRequest.getEndTime()))
            conditionStep = conditionStep.and(LOAN_DISTRIBUTION_RECORD.CREATE_TIME.le(new Timestamp(searchRequest.getEndTime().getTime())));
        if (StringUtils.isNotBlank(searchRequest.getSuperiorPhoneNumber()))
            conditionStep = conditionStep.and(LOAN_DISTRIBUTION_RECORD.SUBORDINATE_PHONE.eq(searchRequest.getSuperiorPhoneNumber()));
        if (StringUtils.isNotBlank(searchRequest.getSubordinatePhoneNumber()))
            conditionStep = conditionStep.and(LOAN_DISTRIBUTION_RECORD.SUBORDINATE_PHONE.eq(searchRequest.getSubordinatePhoneNumber()));
        if (Objects.nonNull(searchRequest.getDistributionActivityId()))
            conditionStep = conditionStep.and(LOAN_DISTRIBUTION_RECORD.DISTRIBUTION_ID.eq(searchRequest.getDistributionActivityId()));
        if (Objects.nonNull(searchRequest.getChannelIds()) && !searchRequest.getChannelIds().isEmpty())
            conditionStep = conditionStep.and(LOAN_DISTRIBUTION_RECORD.CHANNEL.in(searchRequest.getChannelIds()));
        if (Objects.nonNull(searchRequest.getPlatforms()) && !searchRequest.getPlatforms().isEmpty())
            conditionStep = conditionStep.and(LOAN_DISTRIBUTION_RECORD.PLATFORM.in(searchRequest.getPlatforms()));
        if (Objects.nonNull(searchRequest.getProductIds()) && !searchRequest.getProductIds().isEmpty())
            conditionStep = conditionStep.and(LOAN_DISTRIBUTION_RECORD.PRODUCT.in(searchRequest.getProductIds()));
        @SuppressWarnings("unchecked")
		SelectQuery query = conditionStep.orderBy(LOAN_DISTRIBUTION_RECORD.CREATE_TIME.desc()).getQuery();

        return search(query, pageable, record -> {
            GalaxyCardDistributionRecordSearchResponse response = new GalaxyCardDistributionRecordSearchResponse();
            response.setId(record.get(LOAN_DISTRIBUTION_RECORD.ID));
            response.setChannel(record.get(COMM_PRODUCT_CHANNEL.CHANNEL_NAME));
            response.setProduct(record.get(COMM_PRODUCT_PRDID.NAME));
            response.setPlatform(record.get(LOAN_DISTRIBUTION_RECORD.PLATFORM));
            response.setCommission(record.get(LOAN_DISTRIBUTION_RECORD.COMMISSION));
            response.setCreateTime(record.get(LOAN_DISTRIBUTION_RECORD.CREATE_TIME));
            response.setOrderId(record.get(LOAN_DISTRIBUTION_RECORD.ORDER_ID));
            response.setShareType(ShareType.get(record.get(LOAN_DISTRIBUTION_RECORD.SHARE_TYPE)));
            
            String superiorPhoneNumber = record.get(LOAN_DISTRIBUTION_RECORD.SUPERIOR_PHONE);
            String subordinatePhoneNumber = record.get(LOAN_DISTRIBUTION_RECORD.SUBORDINATE_PHONE);
            response.setSuperiorPhoneNumber(PhoneNumNideUtil.hideNum(superiorPhoneNumber));
            response.setSubordinatePhoneNumber(PhoneNumNideUtil.hideNum(subordinatePhoneNumber));
            return response;
        });
    }

    @Override
    protected TableImpl getTable() {
        return LOAN_DISTRIBUTION_RECORD;
    }
}
